package ynet

import (
	"errors"
	"fmt"
	"golang-zinx-demo/yanx/yiface"
	"sync"
)

/*
	连接管理模块
*/

type ConnManager struct {
	// 管理的链接集合
	connections map[uint32]yiface.IConnection
	// 保护连接集合的读写锁
	connLock sync.RWMutex
}

// 创建当前连接的方法
func NewConnManager() *ConnManager {
	return &ConnManager{
		connections: make(map[uint32]yiface.IConnection),
	}
}

// 增加连接
func (cm *ConnManager) Add(conn yiface.IConnection) {
	// 保护共享资源map，加写锁
	cm.connLock.Lock()
	defer cm.connLock.Unlock()

	// 将conn加入到ConnManager中
	cm.connections[conn.GetConnID()] = conn
	fmt.Printf("conniction id = %d add to ConnManager successful: conn num = %d\n", conn.GetConnID(), cm.Len())
}

// 删除连接
func (cm *ConnManager) Remove(conn yiface.IConnection) {
	// 保护共享资源map，加写锁
	cm.connLock.Lock()
	defer cm.connLock.Unlock()

	// 将conn从ConnManager中删除
	delete(cm.connections, conn.GetConnID())
	fmt.Printf("delete conniction id = %d from ConnManager successful: conn num = %d\n", conn.GetConnID(), cm.Len())
}

// 更根据connID获取连接
func (cm *ConnManager) Get(connID uint32) (yiface.IConnection, error) {
	// 保护共享资源map，加读锁
	cm.connLock.RLock()
	defer cm.connLock.RUnlock()

	if conn, ok := cm.connections[connID]; ok {
		return conn, nil
	}
	return nil, errors.New("connection not found!!!")
}

// 获取当前连接总数
func (cm *ConnManager) Len() int {
	return len(cm.connections)
}

// 清除并终止所有连接
func (cm *ConnManager) CLearConn() {
	// 保护共享资源map，加写锁
	cm.connLock.Lock()
	defer cm.connLock.Unlock()

	// 删除所有conn并停止conn的工作
	for connID, conn := range cm.connections {
		// 停止
		conn.Stop()
		// 删除
		delete(cm.connections, connID)
	}
}
